#! /usr/bin/python3.7
# -*- coding: utf-8 -*-

import json
import RPi.GPIO as GPIO
import time
import requests

# GPIO通道定义，36为烟雾传感器，38为温度传感器
CHANNEL_tmp = 38
CHANNEL_smoke = 36
# 温度传感器GPIO_tmp，烟雾传感器GPIO_smoke
GPIO_tmp = GPIO
GPIO_smoke = GPIO
# 初始化记录时间
recordTime = 0
# 记录温度、烟雾异常状态，0正常，1异常。
record_time = {"last_curr_tmp_time": recordTime, "last_curr_smoke_time": recordTime}
# 异常标志
record_status = [0, 0]
# 后端地址
SERVER_URL = "http://101.200.82.120:9999"
HEADERS = {
    'Content-Type': 'application/json'
}
# 上报数据模板
template = {"postTime": 0, "dataType": 0, "dataValue": 0}


# 初始化GPIO对象及对应参数（GPIO引脚通道、针脚模式，初始化低电平）
def init():
    GPIO_tmp.setmode(GPIO.BOARD)
    GPIO_smoke.setmode(GPIO.BOARD)
    GPIO_tmp.setup(CHANNEL_tmp, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO_smoke.setup(CHANNEL_smoke, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    return [GPIO_smoke, GPIO_tmp]


# 上报正常数据的周期
def check_time_period(curr_time):
    thisTime = int(round(time.time() * 1000))
    # 距离上次记录时间已经超过或等于5分钟
    if curr_time + 300000 <= thisTime:
        return True
    else:
        return False


# 上报数据方法
# need_change_time: 0不改变 1更新正常温度时间及状态 2更新正常空气时间及状态
def post_sensor_data(data_type, data_value, need_change_time):
    toPost = template
    toPost['postTime'] = (int(round(time.time() * 1000)))
    toPost['dataType'] = data_type
    toPost['dataValue'] = data_value
    try:
        post_url = SERVER_URL + "/postSensorData"
        print(post_url)
        requests.request("POST", post_url, headers=HEADERS, data=json.dumps(toPost))
        # response = requests.request("POST", post_url, headers=HEADERS, data=json.dumps(toPost))
        # print("上传成功:", response.text.encode('utf8'))
    except Exception as exp:
        print("Exception:", exp)
    finally:
        if need_change_time == 1:
            record_time['last_curr_tmp_time'] = int(round(time.time() * 1000))
            record_status[0] = 0
        elif need_change_time == 2:
            record_time['last_curr_smoke_time'] = int(round(time.time() * 1000))
            record_status[1] = 0


# 温度：0升温 1常温
# 烟雾：0异常 1正常
if __name__ == "__main__":
    GPIOs = init()
    while True:
        try:
            status_tmp = GPIOs[1].input(CHANNEL_tmp)
            status_smoke = GPIOs[0].input(CHANNEL_smoke)
            print("tmp: ", status_tmp)
            print("smoke: ", status_smoke)
            if status_tmp:
                # 环境温度小于等于电位器设定温度
                if record_status[0] != 0:
                    # 上传一条正常温度记录
                    post_sensor_data(0, 0, 1)
                else:
                    if check_time_period(record_time['last_curr_tmp_time']):
                        post_sensor_data(0, 0, 1)
            else:
                print("==================")
                print("Temp Error", status_tmp)
                print("==================")
                # 上传一条温度异常记录
                record_time['last_curr_tmp_time'] = int(round(time.time() * 1000))
                post_sensor_data(0, 1, 0)
                record_status[0] = 1
            if status_smoke:
                # 烟雾密度小于等于灵敏度阈值
                if record_status[1] != 0:
                    # 上传一条正常空气记录
                    post_sensor_data(1, 0, 2)
                else:
                    if check_time_period(record_time['last_curr_smoke_time']):
                        post_sensor_data(1, 0, 2)
            else:
                print("==================")
                print("Air Error", status_smoke)
                print("==================")
                # 上传一条空气异常记录
                record_time['last_curr_smoke_time'] = int(round(time.time() * 1000))
                post_sensor_data(1, 1, 0)
                record_status[1] = 1
            time.sleep(1)
        except Exception as e:
            print("error: ", e)
            # 清除GPIO信息
            GPIO_tmp.cleanup()
            GPIO_smoke.cleanup()
            # 重新初始化GPIO
            init()
            continue
